cc.Class({
    extends: cc.Component,

    properties: {
        textures: cc.SpriteAtlas,
        sprite: cc.Sprite
    },

    onLoad() {
        this.body = this.node.getComponent(cc.RigidBody)

        this.speed = 200
        this.acceleration = {x: 8, y: 0}
        this.jumpable = 0
        this.direction = 0
        this.lastDirection = 1
        this.rotate = false

        this.frames = [
            this.textures.getSpriteFrame('playerRed_walk3'),
            this.textures.getSpriteFrame('playerRed_walk2'),
            this.textures.getSpriteFrame('playerRed_walk1')
        ]

        this.walkState = {
            i: 0,
            step: 1
        }

        this.listen()
    },

    start() {
        // this.node.runAction(cc.flipX(true))
        // this.walk()
    },

    walk() {
        this.sprite.spriteFrame = this.frames[this.walkState.i]
        if (this.direction && this.land) {
            this.walkState.i === 0 ? this.walkState.step = 1 :
            this.walkState.i === 2 ? this.walkState.step = -1 : null
            this.walkState.i += this.walkState.step
        } else if (this.land) {
            this.walkState.i = 0
        } else {
            this.walkState.i = 2
        }
    },


    listen() {
        this.node.on('left', ev => {
            this.lastDirection = this.direction
            this.direction = -1
            if (this.lastDirection !== this.direction) this.sprite.node.runAction(cc.flipX(true))
        })

        this.node.on('right', ev => {
            this.lastDirection = this.direction
            this.direction = 1
            if (this.lastDirection !== this.direction) this.sprite.node.runAction(cc.flipX(false))
        })

        this.node.on('stand', ev => {
            this.direction = 0
        })

        this.node.on('jump', ev => {
            const
                mass = this.body.getMass(),
                y = this.body.linearVelocity.y

            if (this.land && cc.equal(y, 0, 1)) {
                this.land = false
                this.body.applyLinearImpulse(
                    {x: mass * this.direction * this.speed, y: mass * 500},
                    this.body.getWorldPosition(),
                    true
                )
            } else {
                console.log('旋转')
            }
        })
    },

    onBeginContact(contact, self, other) {
        self.sensor && (this.land = true)
    },

    onEndContact(contact, self, other) {
        self.sensor && (this.land = false)
    },

    update() {
        const v = this.body.linearVelocity

        if (this.land) {
            let x = Math.abs(v.x)
            x < this.speed ? x += this.acceleration.x : x = this.speed
            v.x = x * this.direction
        } else if (this.direction) {
            v.x += this.direction * 8
        }

        v.x > this.speed ? v.x = this.speed :
        v.x < -this.speed ? v.x = -this.speed : null

        this.body.linearVelocity = v

        this.walk()
    }
})
